package cn.monkey.chat.server.connect.chat.filter;

import cn.monkey.chat.server.connect.chat.ChatExchange;
import cn.monkey.chat.server.data.account.UserSession;
import cn.monkey.chat.server.proto.Message;
import cn.monkey.chat.server.proto.Package;
import cn.monkey.chat.server.proto.User;
import cn.monkey.io.transport.core.server.FilterChain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class GroupOrPrivateChatMessageFilter implements ChatMessageFilter {
    private static final Logger log = LoggerFactory.getLogger(GroupOrPrivateChatMessageFilter.class);

    @Override
    public void doFilter(ChatExchange exchange, Package pkg, FilterChain<ChatExchange, Package> filterChain) {
        UserSession userSession = exchange.getAttribute(UserSession.KEY);
        List<String> friends = userSession.getFriends();
        List<String> groups = userSession.getGroups();
        if (groups == null && friends == null) {
            log.error("can not send pkg to group or private chat");
            return;
        }
        String groupId = pkg.getGroupId();
        if (groupId != null && groups != null && !groups.contains(groupId)) {
            log.error("can not send pkg to group: {}", groupId);
            return;
        }
        Object data = pkg.getData();
        if (data instanceof Message message) {
            List<User> messageTo = message.getTo();
            if (messageTo == null || messageTo.size() != 1) {
                log.error("invalid private chat pkg: {}", pkg);
                return;
            }
            User first = messageTo.getFirst();
            if (friends != null && !friends.contains(first.getUid())) {
                log.error("can not send private chat message to uid: {}", first.getUid());
                return;
            }
        }
        filterChain.doFilter(exchange, pkg);
    }
}
